package com.jielihaofeng.websocket.service;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @description WebSocket服务ws://localhost:18080/api/websocket/100
 * @author Johnnie Wind
 * @date 2021/1/11 17:46
 */
@Component
@Service
@ServerEndpoint("/api/websocket/{sid}")
public class WebSocketServer {

    private static AtomicInteger onlineCount = new AtomicInteger();

    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();

    private Session session;

    private String sid;


    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid){
        this.session=session;
        webSocketSet.add(this);
        this.sid =sid;
        addOnlineCount();
        try{
            sendMessage("conn_success");
            System.out.println("有新窗口开始监听："+sid+"当前在线人数为："+getOnlineCount());
        }catch (Exception e){
            e.printStackTrace();
            System.err.println(e);
        }
    }

    @OnClose
    public void onClose(){
        webSocketSet.remove(this);
        subOnlineCount();
        System.out.println("释放sid"+sid);
        System.out.println("有一连接关闭！当前在线人数为："+getOnlineCount());
    }

    @OnMessage
    public void onMessage(String message, Session session){
        System.out.println("收到来自窗口"+sid+"的信息"+message);
        for (WebSocketServer item:webSocketSet){
            try{
                item.sendMessage(message);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    @OnError
    public void onError(Session session,Throwable error){
        System.err.println("发生错误");
        error.printStackTrace();
    }

    public void sendMessage(String message) throws IOException{
        this.session.getBasicRemote().sendText(message);
    }

    public static void sendInfo(String message,@PathParam("sid") String sid) throws IOException{
        System.out.println("推送消息到端口"+sid+"，推送内容："+message);
        for (WebSocketServer item: webSocketSet){
            try {
                if (sid==null){
//                    item.sendMessage(message);
                }else if (item.sid.equals(sid)){
                    item.sendMessage(message);
                }
            }catch (IOException e){
                continue;
            }
        }
    }

    public static synchronized int getOnlineCount(){
        return onlineCount.get();
    }

    public static synchronized void addOnlineCount(){
        WebSocketServer.onlineCount.incrementAndGet();
    }

    public static synchronized void subOnlineCount(){
        WebSocketServer.onlineCount.decrementAndGet();
    }

    public static CopyOnWriteArraySet<WebSocketServer> getWebSocketSet(){
        return webSocketSet;
    }

}
